import { OrtcService } from './services/ortc.service';
import { Component, HostListener, OnInit } from '@angular/core';
import {MatDialog, MAT_DIALOG_DATA} from '@angular/material/dialog';
import {RequestReplyService} from './services/request-reply.service';
import {EventSource, EventService, EventMessage} from './services/event.service';
import {BookedService} from './services/booked.service';
import {User} from './entity/TT';
import { MessageDialogComponent, DialogData } from './dialog/message-dialog/message-dialog.component';
import { ConferenceListComponent, ConferenceListData } from "./dialog/conference-list/conference-list.component";
import { ChatService } from './services/chat.service';

import { NGXLogger } from 'ngx-logger';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent  implements OnInit {
  title = 'OkEDU-Classroom-Web';

  me: User;

  loading = false;
  login = false;

  constructor(
    private chatService: ChatService,
    private requestService: RequestReplyService,
    private eventService: EventService,
    private rtcService: OrtcService,
    private log: NGXLogger,
    public dialog: MatDialog
    )
    {
      this.log.debug('AppComponent...');
      this.init();
    }

  ngOnInit() {
    this.log.debug('AppComponent ngOnInit...');
  }

  @HostListener("window:beforeunload", ["$event"])
  beforeunloadHandler(event: Event) {
    this.log.debug('beforeunload', event);
    // event.returnValue = true;
    // return true;

    this.eventService.sendEvent(EventSource.UNLOAD, 0);
    this.rtcService.dispose();

  }

  @HostListener("window:unload", ["$event"])
  unloadHandler(event: Event) {
    // this.log.debug('unload', event);

    // this.eventService.sendEvent(EventSource.UNLOAD, 0);
    // this.rtcService.dispose();
  }

  init() {


    this.loading = true;
    this.requestService.GetMe().subscribe((me: User) => {
      setTimeout( () => {
        this.loading = false;
        if (me) {
          this.me = me;
          this.eventService.sendLogin(me);
        } else {
          this.login = true;
        }
      },  400);

   });

    this.eventService.subscribeLogin((me: User) => {
      this.log.debug('subscribeLogin', me);
      // this.bookedService.refresh();
      this.chatService.init(me);
      return true;
    });


    this.eventService.subscribeExit(() => {
      this.log.debug('subscribeExit ...');
      this.requestService.Logout()
        .subscribe((reply) => {
          if(reply.success){
            this.refresh()
          }
        })
    });

    this.eventService.subscribeEvent((msg: EventMessage) => {
      switch (msg.source) {
        case EventSource.ERROR:
          this.openDialog(msg.data);
          break;
        case EventSource.CONFERENCE_LIST:
          this.openConferenceList(msg.data);
          break;
      }
    });
  }

  openConferenceList(list: any) {
    this.log.debug('openConferenceList', list);
    const data: ConferenceListData = {
      message: list,
      userTypes:   [
        {name: 'Teacher', text:"教师"},
        {name: 'Member', text:"学员"}
        ]};

    this.dialog.open(ConferenceListComponent, {
      width: '560px',
      data
    });
  }


  openDialog(msg: any) {

    const data: DialogData = {message: msg};

    const dialogRef = this.dialog.open(MessageDialogComponent, {
      width: '250px',
      data
    });

    dialogRef.afterClosed().subscribe(result => {
      this.log.debug('The dialog was closed', result);
    });

  }

  refresh(){
    setTimeout(()=>{
      location.href = '/';
    }, 200)
  }

}
